package com.zhang.sequencegenerate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhang.sequencegenerate.constant.SequenceRuleConstant;
import com.zhang.sequencegenerate.entity.SequenceRule;
import com.zhang.sequencegenerate.enums.ModuleEnum;
import com.zhang.sequencegenerate.mapper.SequenceRuleMapper;
import com.zhang.sequencegenerate.service.SequenceRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author Mr.Zhang
 * @Date 2025/5/24 23:48
 * @Version 1.0
 */
@Service
public class SequenceRuleServiceImpl extends ServiceImpl<SequenceRuleMapper, SequenceRule> implements SequenceRuleService {

    @Autowired
    private SequenceRuleMapper sequenceRuleMapper;

    /**
     * 根据枚举条件获取序列规则
     *
     * @param moduleEnum 模块枚举
     * @return 序列规则
     */
    @Override
    public SequenceRule getByModuleEnum(ModuleEnum moduleEnum) {
        // 查询模块 ID 对应的序列规则
        SequenceRule sequenceRule = this.getByModuleId(moduleEnum.getModuleId());
        if (sequenceRule == null) {
            // 不存在则使用默认规则
            sequenceRule = new SequenceRule();
            sequenceRule.setModuleId(moduleEnum.getModuleId());
            sequenceRule.setRule(SequenceRuleConstant.DEFAULT_RULE);
            sequenceRule.setCuid(1);
            sequenceRule.setPref("");
            this.save(sequenceRule);
        }
        return sequenceRule;
    }

    /**
     * 根据模块 ID 获取序列规则
     *
     * @param moduleId 模块 ID
     * @return 模块 ID 对应的序列规则
     */
    private SequenceRule getByModuleId(String moduleId) {
        LambdaQueryWrapper<SequenceRule> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SequenceRule::getModuleId, moduleId);
        return sequenceRuleMapper.selectOne(queryWrapper);
    }
}
